package com.yunxin.admin.system.infra.persistence.repository;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.admin.system.domain.model.role.Role;
import com.yunxin.admin.system.domain.model.role.RoleRepository;
import com.yunxin.admin.system.infra.persistence.converter.RoleConverter;
import com.yunxin.admin.system.infra.persistence.entity.SysRoleDO;
import com.yunxin.admin.system.infra.persistence.mapper.SysRoleMapper;
import com.yunxin.core.admin.domain.AdminUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

/**
 * @author zero°
 * @since 2023-07-11
 */
@Repository
@RequiredArgsConstructor
public class RoleRepositoryImpl extends ServiceImpl<SysRoleMapper, SysRoleDO> implements RoleRepository, IService<SysRoleDO> {

    private final RoleConverter roleConverter;

    @Override
    public boolean saveOrUpdate(Role role) {
        long count = this.count(new LambdaQueryWrapper<SysRoleDO>()
                .ne(role.getId() != null, SysRoleDO::getId, role.getId())
                .and(wrapper -> wrapper.eq(SysRoleDO::getName, role.getName())));
        Assert.isTrue(count == 0, "角色名称或角色编码重复，请检查！");
        SysRoleDO sysRoleDO = roleConverter.formRole(role);
        return this.saveOrUpdate(sysRoleDO);
    }

    @Override
    public boolean removeByIdList(Collection<Long> ids) {
        return this.removeByIds(ids);
    }

    @Override
    public boolean updateStatus(Long id, Integer status) {
        return this.update(new LambdaUpdateWrapper<SysRoleDO>()
                .eq(SysRoleDO::getId, id)
                .set(SysRoleDO::getStatus, status));
    }

    @Override
    public List<AdminUser> userListByRoleCode(String code,Integer teamId) {
        return baseMapper.userListByRoleCode(code,teamId);
    }

    @Override
    public List<AdminUser> getUserList(String code, List<Integer> teamIds) {
        return baseMapper.getUserList(code,teamIds);
    }

    @Override
    public List<AdminUser> telephoneListBySalesmanId(String code, List<Integer> userIds,Integer teamId) {
        return baseMapper.telephoneListBySalesmanId(code,userIds,teamId);
    }

    @Override
    public  List<Long> getUserRoles(Long id) {
        return baseMapper.getUserRoles(id);
    }
}
